﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;
using System.Web;

namespace EmaMetadata.Serializers
{
    public class BaseSerializer
    {
        #region Defined interfaces
        /// <summary>
        /// Loads an EMA batch from the document
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        public virtual EmaBatch Load(XmlDocument d)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Saves an EMA batch to an XML object
        /// </summary>
        /// <param name="xw"></param>
        /// <param name="b"></param>
        public virtual void Save(XmlWriter xw, EmaBatch b)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Writes a single EMA Product to an XML object
        /// </summary>
        /// <param name="xw"></param>
        /// <param name="p"></param>
        public virtual void WriteProduct(XmlWriter xw, EmaProduct p)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Writes a single EMA Product to an XML object
        /// </summary>
        /// <param name="xw"></param>
        /// <param name="p"></param>
        public virtual EmaProduct ReadProduct(XmlNode n)
        {
            throw new NotImplementedException();
        }
        #endregion

        #region Helper functions
        /// <summary>
        /// Retrieve the appropriate serializer to use for this revision of the data format
        /// </summary>
        /// <param name="RecordVersion"></param>
        /// <returns></returns>
        public static BaseSerializer Get(string RecordVersion)
        {
            // If no record version supplied, assume the latest version we have
            if (string.IsNullOrEmpty(RecordVersion)) {
                return new Version4();
            }

            // Version 4
            if (RecordVersion == "4") {
                return new Version4();
            }

            // All others fail
            return null;
        }

        /// <summary>
        /// Shortcut to retrieve the current version serializer
        /// </summary>
        public static BaseSerializer Current
        {
            get
            {
                return Get(null);
            }
        }

        /// <summary>
        /// Convenience function for fixing up XML text into valid XML text
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        protected static string XmlFixup(string s)
        {
            return HttpUtility.HtmlEncode(Regex.Replace(s, @"[\u0000-\u0008,\u000B,\u000C,\u000E-\u001F]", ""));
        }
        #endregion
    }
}
